#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import print_function, absolute_import
from gm.api import *
from web.config.commodity_future_date_contract_data_config import CommodityFutureDateContractDataConfig
from web.config.myquant_config import MyQuantConfig
from web.util.char_util import CharUtil
from web.manager.log_manager import LogManager
from web.task.base_task import BaseTask

Logger = LogManager.get_logger(__name__)

"""
调用掘金量化的接口，下载商品期货交易的合约数据
"""


class MyQuantDownloadCollectCommodityFutureDateContractDataTask(BaseTask):

    def download_data(self):
        """
        调用掘金量化的接口，下载商品期货交易的合约数据
        """

        Logger.info('调用掘金量化的接口，下载商品期货交易的合约数据')

        # 掘金终端需要打开，接口取数是通过网络请求的方式
        # 设置token，可在用户-密钥管理里查看获取已有token ID
        set_token(MyQuantConfig.MyQuant_Token)
        # 查询交易所列表
        commodity_future_exchange_list = self.commodity_future_exchange_service.commodity_future_exchange_dao.find_list(
            dict(), dict(), list())
        for commodity_future_exchange in commodity_future_exchange_list:
            # 查询交易所期货合约列表
            # 股指期货、国债期货（注意：只有中金所有股指期货和国债期货）
            code_symbol_list = get_symbol_infos(1040, sec_type2=104001, exchanges=commodity_future_exchange.code,
                                                symbols=None, df=False)
            code_symbol_list.extend(get_symbol_infos(1040, sec_type2=104006, exchanges=commodity_future_exchange.code,
                                                symbols=None, df=False))

            # 商品期货
            if len(code_symbol_list) == 0:
                code_symbol_list = get_symbol_infos(1040, sec_type2=104003, exchanges=commodity_future_exchange.code,
                                                    symbols=None, df=False)

            if code_symbol_list is not None and len(code_symbol_list) > 0:
                for code_symbol in code_symbol_list:
                    # 如果不是具体合约，则跳过
                    code = code_symbol.symbol.split(".")[1]
                    english = CharUtil.remove_spaces(CharUtil.extract_alpha(code))
                    number = CharUtil.extract_numbers(code)
                    if len(number) >= 3:
                        # 查询具体合约的数据
                        commodity_future_date_contract_data_data_frame = history(symbol=code_symbol.symbol,
                                                                                frequency='1d',
                                                                                start_time=CommodityFutureDateContractDataConfig.Commodity_Future_Date_Contract_Data_Basic_Data_Begin_Date,
                                                                                end_time=CommodityFutureDateContractDataConfig.Commodity_Future_Date_Contract_Data_Basic_Data_End_Date,
                                                                                fields='symbol, open, close, low, high, amount, volume, position, eob',
                                                                                adjust=ADJUST_PREV, df=True)
                        # 查询期货合约的中文名称
                        where_list = ["UPPER(code) = '" + english.upper() + "'"]
                        commodity_future_info_list = self.commodity_future_info_service.commodity_future_info_dao.extra_list(where_list)
                        if commodity_future_info_list is not None and len(commodity_future_info_list):
                            commodity_future_info = commodity_future_info_list[0]
                            # 存储记录
                            self.commodity_future_date_contract_data_service.save_commodity_future_date_contract_data_list_for_my_quant(
                                commodity_future_date_contract_data_data_frame.values.tolist(), commodity_future_info.name + number)
                        else:
                            Logger.warn("期货[%s]在表commodity_future_info中没有查到对应的记录，跳过", code_symbol.symbol)
                    else:
                        Logger.warn("期货[%s]不是具体的合约，不存储", code_symbol.symbol)
            else:
                Logger.warn("交易所[%s]没有取货数据", commodity_future_exchange.code)
